// 创建路由配置
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import PublicActivities from '@/views/PublicActivities.vue'
import PublicActivityDetail from '@/views/PublicActivityDetail.vue'
import ActivityManagement from '@/views/ActivityManagement.vue'
import Parent from '@/components/Parent.vue'
import Child from '@/components/Child.vue'

Vue.use(Router)

const routes = [
  { path: '/login', component: Login },
  { path: '/', component: Home, meta: { requiresAuth: true } },
  { path: '/public-activities', component: PublicActivities },
  { path: '/public-activities/:id', component: PublicActivityDetail },
  {
    path: '/activity-management',
    component: ActivityManagement,
    meta: { requiresAdmin: true }
  }
]

const router = new Router({
  mode: 'history',
  routes
})

// 添加导航守卫，在每次路由跳转前执行此函数
router.beforeEach((to, from, next) => {
  // 检查 localStorage 中是否存在 userRole 来判断用户是否已认证
  const isAuthenticated = !!localStorage.getItem('userRole')
  // 从 localStorage 中获取用户角色
  const userRole = localStorage.getItem('userRole')

  // 如果目标路由需要认证
  if (to.meta.requiresAuth) {
    // 如果用户未认证
    if (!isAuthenticated) {
      // 重定向到登录页面
      next('/login')
    } else {
      // 已认证则继续跳转
      next()
    }
  }
  // 如果目标路由需要管理员权限
  else if (to.meta.requiresAdmin) {
    // 如果用户角色是管理员
    if (userRole === 'admin') {
      // 继续跳转
      next()
    } else {
      // 不是管理员则重定向到首页
      next('/')
    }
  }
  // 目标路由既不需要认证也不需要管理员权限
  else {
    // 直接继续跳转
    next()
  }
})

export default router